package com.tomorrowbbs.controller;

import com.tomorrowbbs.annotation.GlobalInterceptor;
import com.tomorrowbbs.annotation.VerifyParam;
import com.tomorrowbbs.controller.base.ABaseController;
import com.tomorrowbbs.domain.*;
import com.tomorrowbbs.domain.config.WebConfig;
import com.tomorrowbbs.domain.constants.Constants;
import com.tomorrowbbs.domain.dto.SessionWebUserDto;
import com.tomorrowbbs.domain.enums.*;
import com.tomorrowbbs.domain.vo.PaginationResultVo;
import com.tomorrowbbs.domain.vo.ResponseVo;
import com.tomorrowbbs.domain.vo.web.ForumArticleAttachmentVo;
import com.tomorrowbbs.domain.vo.web.ForumArticleDetailVO;
import com.tomorrowbbs.domain.vo.web.ForumArticleVO;
import com.tomorrowbbs.domain.vo.web.UserDownloadInfoVO;
import com.tomorrowbbs.exception.BusinessException;
import com.tomorrowbbs.service.*;
import com.tomorrowbbs.service.impl.ForumBoardServiceImpl;
import com.tomorrowbbs.utils.CopyTools;
import com.tomorrowbbs.utils.StringTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.Cookie;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/forum")
public class ForumArticleController extends ABaseController {
    private static final Logger logger = LoggerFactory.getLogger(ForumArticleController.class);
    @Autowired
    private IForumArticleService forumArticleService;
    @Autowired
    private IForumArticleAttachmentService forumArticleAttachmentService;
    @Autowired
    private ILikeRecordService likeRecordService;
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IForumArticleAttachmentDownloadService forumArticleAttachmentDownloadService;
    @Autowired
    private WebConfig webConfig;
    @Autowired
    private ForumBoardServiceImpl forumBoardServiceImpl;


    @RequestMapping("/loadArticle")
    public ResponseVo loadArticle(HttpSession session,Long boardId,Long pBoardId,Integer orderType, Integer pageNo){
        ForumArticle article = new ForumArticle();
        article.setBoardId(boardId == null || boardId == 0 ? null : boardId);
        article.setPBoardId(pBoardId);
//        article.setPageNo(pageNo);

        // 判断是否登录，查询当前用户的待审核的文章
        SessionWebUserDto userDto = getUserInfoFromSession(session);
        if (userDto != null){
            article.setCurrentUserId(userDto.getUserId());
        }else {
            article.setStatus(ArticleStatusEnum.AUDIT.getStatus());
        }

        ArticleOrderTypeEnum orderTypeEnum = ArticleOrderTypeEnum.getByType(orderType);
        orderTypeEnum = orderTypeEnum == null ? ArticleOrderTypeEnum.HOT : orderTypeEnum;
        article.setOrderBy(orderTypeEnum.getOrderSql());

        if (pageNo != null ){
            pageNo = pageNo;
        }else {
            pageNo = 1;
        }
        // 设置分页参数
        int pageSize =15;
        int offset = (pageNo - 1) * pageSize;
        article.setOffset(offset);
        article.setLimit(pageSize);

        article.setPageNo(pageNo);
        // 获取文章列表
        List<ForumArticle> articles = forumArticleService.selectArticlePageList(article);
        // 获取总记录数
        int totalCount = forumArticleService.countForumArticles(article);
        // 构建分页结果
        PaginationResultVo<ForumArticle> paginationResultVo = getForumArticlePaginationResultVo(pageNo, totalCount, articles, pageSize);
        return getSuccessResponseVo(convert2PaginationVO(paginationResultVo, ForumArticleVO.class));
    }

    /*
    * 获取文章详情*/
    @RequestMapping("/getArticleDetail")
    @GlobalInterceptor(checkParams = true)
    public ResponseVo getArticleDetail(HttpSession session,@VerifyParam(required = true) String articleId){

        SessionWebUserDto sessionWebUserDto = getUserInfoFromSession(session);
        ForumArticle forumArticle = forumArticleService.readArticle(articleId);
        //判断是否可以展示文章
//        Boolean showAudit = sessionWebUserDto != null && sessionWebUserDto.getUserId().equals(forumArticle.getUserId()) || sessionWebUserDto.getIsAdmin();

        if(null == forumArticle ||(ArticleStatusEnum.NO_AUDIT.getStatus().equals(forumArticle.getStatus()) &&
                (sessionWebUserDto==null || !sessionWebUserDto.getUserId().equals(forumArticle.getUserId())||!sessionWebUserDto.getIsAdmin()))
                || ArticleStatusEnum.DEL.getStatus().equals(forumArticle.getStatus())){
            throw new BusinessException(ResponseCodeEnum.CODE_404);
        }

        ForumArticleDetailVO detailVO = new ForumArticleDetailVO();
        detailVO.setForumArticleVO(CopyTools.copy(forumArticle, ForumArticleVO.class));
        //判断是否有附件
        if (forumArticle.getAttachmentType() == Constants.ONE){
            ForumArticleAttachment articleAttachment = new ForumArticleAttachment();
            articleAttachment.setArticleId(articleId);
            List<ForumArticleAttachment> forumArticleAttachmentList = forumArticleAttachmentService.selectForumArticleAttachmentList(articleAttachment);
            if(!forumArticleAttachmentList.isEmpty()){
                detailVO.setAttachmentVo(CopyTools.copy(forumArticleAttachmentList.get(0), ForumArticleAttachmentVo.class));
            }
        }

        //判断是否已经点赞
        if (sessionWebUserDto != null){
            LikeRecord likeRecord = new LikeRecord();
            likeRecord.setObjectId(articleId);
            likeRecord.setUserId(sessionWebUserDto.getUserId());
            likeRecord.setOpType(OperRecordOpTypeEnum.ARTICLE_LIKE.getType());
            LikeRecord likeRecord1 = likeRecordService.selectLikeRecord(likeRecord);
            System.out.println("likeRecord1:"+likeRecord1);
            if(likeRecord1 != null ){
                detailVO.setHaveLike(true);
            }
        }
        return getSuccessResponseVo(detailVO);
    }

    /*
    *点赞 */
    @RequestMapping("/doLike")
    @GlobalInterceptor(checkLogin = true,checkParams = true)
    public ResponseVo doLike(HttpSession session,@VerifyParam(required = true) String articleId){
        SessionWebUserDto sessionWebUserDto = getUserInfoFromSession(session);

        likeRecordService.doLike(articleId,sessionWebUserDto.getUserId(),sessionWebUserDto.getNickName(),OperRecordOpTypeEnum.ARTICLE_LIKE);
        return getSuccessResponseVo(null);
    }

    /*
    * 附件下载
    * */
    @RequestMapping("/getUserDownloadInfo")
    @GlobalInterceptor(checkLogin = true,checkParams = true)
    public ResponseVo getUserDownloadInfo(HttpSession session,@VerifyParam(required = true) String fileId){
        SessionWebUserDto webUserDto = getUserInfoFromSession(session);
        UserInfo userInfo = userInfoService.selectUserInfoByUserId(webUserDto.getUserId());
        UserDownloadInfoVO downloadInfoVO = new UserDownloadInfoVO();
        downloadInfoVO.setUserIntegral(userInfo.getCurrentIntegral());

        ForumArticleAttachmentDownload download = forumArticleAttachmentDownloadService.selectForumArticleAttachmentDownloadByInfo(fileId,webUserDto.getUserId());
        if (download != null){
            downloadInfoVO.setHaveDownload(true);
        }

        return getSuccessResponseVo(downloadInfoVO);
    }

    @RequestMapping("/attachmentDownload")
    @GlobalInterceptor(checkLogin = true,checkParams = true)
    public void attachmentDownload(HttpSession session, HttpServletRequest request, HttpServletResponse response,
                                   @VerifyParam(required = true) String fileId){
        ForumArticleAttachment attachment = forumArticleAttachmentService.downloadAttachment(fileId,getUserInfoFromSession(session));
        InputStream in = null;
        OutputStream out = null;
        String downloadFileName = attachment.getFileName();
        String filePath = webConfig.getProjectFolder() + Constants.FILE_FOLDER_FILE + Constants.FILE_FOLDER_ATTACHMENT + attachment.getFilePath();
        File file = new File(filePath);
        try{
            in = new FileInputStream(file);
            out  = response.getOutputStream();
            response.setContentType("application/x-msdownload; charset=UTF-8");
            //解决中文乱码
            if(request.getHeader("User-Agent").toLowerCase().indexOf("msie")>0){
                downloadFileName = URLEncoder.encode(downloadFileName, "UTF-8");
            }else {
                downloadFileName = new String(downloadFileName.getBytes("UTF-8"), "ISO-8859-1");
            }
            response.setHeader("content-Disposition","attachment;filename=\"" + downloadFileName + "\"");
            byte[] byteData = new byte[1024];
            int len = 0;
            while ((len = in.read(byteData)) != -1) {
                out.write(byteData, 0, len);
            }
            out.flush();
        }catch (Exception e){
            logger.error("下载异常",e);
            throw new BusinessException("下载失败");
        }finally{
            try{
                if(in!=null){
                    in.close();
                }
            }catch (IOException e){
                logger.error("IO异常",e);
            }
            try{
                if (out!=null){
                    out.close();
                }
            }catch (IOException e){
                logger.error("IO异常",e);
            }
        }


    }

    //获取board
    @RequestMapping("/loadBoard4Post")
    @GlobalInterceptor(checkLogin = true)
    public ResponseVo loadBoard4Post(HttpSession session){
        SessionWebUserDto userDto = getUserInfoFromSession(session);
        Integer postType = null;
        if (!userDto.getIsAdmin()){
            postType = Constants.ONE;
        }

        List<ForumBoard> list = forumBoardServiceImpl.getBoardTree(postType);
        return getSuccessResponseVo(list);
    }

    //发布文章
    @RequestMapping("/postArticle")
    @GlobalInterceptor(checkLogin = true,checkParams = true)
    public ResponseVo postArticle(HttpSession session,
                                  MultipartFile cover,
                                  MultipartFile attachment,
                                  Long integral,
                                  @VerifyParam(required = true, max = 150)String title,
                                  @VerifyParam(required = true) Long pBoardId,
                                  Long boardId,
                                  @VerifyParam(max = 200) String summary,
                                  @VerifyParam(required = true) Integer editorType,
                                  @VerifyParam(required = true) String content,
                                  String markdownContent
                                  ){

        title = StringTools.escapeHtml(title);
        SessionWebUserDto webUserDto = getUserInfoFromSession(session);
        ForumArticle forumArticle = new ForumArticle();
        forumArticle.setTitle(title);
        forumArticle.setPBoardId(pBoardId);
        forumArticle.setBoardId(boardId);
        forumArticle.setContent(content);
        forumArticle.setSummary(summary);
        System.out.println("editorType的值："+editorType);
        EditorTypeEnum typeEnum = EditorTypeEnum.getByType(editorType);
        System.out.println("typeEnum："+typeEnum);

        if (typeEnum == null){
            throw new BusinessException("编辑器类型错误");
        }

        if(EditorTypeEnum.MARKDOWN.getType().equals(editorType) && StringTools.isEmpty(markdownContent)){
            throw new BusinessException("markdown内容不能为空");
        }
        forumArticle.setMarkdownContent(markdownContent);
        forumArticle.setEditorType(editorType);
        forumArticle.setUserId(webUserDto.getUserId());
        forumArticle.setNickName(webUserDto.getNickName());
        forumArticle.setUserIpAddress(webUserDto.getProvince());

        //附件
        ForumArticleAttachment forumArticleAttachment = new ForumArticleAttachment();
        forumArticleAttachment.setIntegral(integral==null?0:integral);
        forumArticleService.postArticle(webUserDto.getIsAdmin(), forumArticle, forumArticleAttachment, cover, attachment);

        return getSuccessResponseVo(forumArticle.getArticleId());
    }



    /*构建分页对象*/
    private static PaginationResultVo<ForumArticle> getForumArticlePaginationResultVo(Integer pageNo, int totalCount, List<ForumArticle> articles ,int pageSize) {
        PaginationResultVo<ForumArticle> paginationResultVo = new PaginationResultVo<>();
        paginationResultVo.setTotalCount(totalCount);
        paginationResultVo.setPageSize(pageSize);
        paginationResultVo.setPageNo(pageNo);
        paginationResultVo.setPageTotal((int) Math.ceil((double) totalCount / paginationResultVo.getPageSize()));
        paginationResultVo.setList(articles);
        return paginationResultVo;
    }
}






















